package indi.mozping.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import indi.mozping.MopzingMongodbApplication;
import indi.mozping.bean.Entity;
import indi.mozping.random.RandomObjFactory;
import indi.mozping.service.AddService;
import indi.mozping.utils.DateUtil;
import indi.mozping.utils.StrUtil;
import indi.mozping.utils.Util;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Map;

/**
 * @author by mozping
 * @Classname AddController
 * @Description TODO
 * @Date 2019/2/22 13:47
 */
@RestController
@RequestMapping("/add")
//@Api(tags = "1.1", description = "新增数据", value = "新增数据")
public class AddController {

    private static final int THREAD_NUM = 20;
    private static final Logger LOG = LoggerFactory.getLogger(AddController.class);
    static ArrayList arr = new ArrayList(512);
    private static final int BATCH = 2000;

    static {
        for (int i = 0; i < arr.size(); i++) {
            arr.add(i);
        }
    }

    @Autowired
    AddService addService;

    @PostMapping
    public JSONObject add(@RequestBody JSONObject param) {
        ArrayList<Entity> arrayList = new ArrayList<>();
        if (param.containsKey("data")) {
            JSONArray data = param.getJSONArray("data");
            for (Object i : data) {
                JSONObject item = (JSONObject) i;
                Entity entity = new Entity();

                entity.setRid(item.getInteger("rid"));
                entity.setCreateName(item.getString("createName"));
                entity.setCreateTime(Util.convertStringToDate(item.getString("createTime")));
                entity.setPeopleNum(item.getInteger("peopleNum"));
                entity.setDeviceNum(item.getInteger("deviceNum"));
                entity.setPeopleName(item.getString("peopleName"));
                entity.setDeviceName(item.getString("deviceName"));

                arrayList.add(entity);
            }
        } else {
            return Util.getFail("请求参数不包含数据!");
        }
        try {
            addService.add(arrayList);
        } catch (Exception e) {
            LOG.warn("新增数据异常...", e);
            return Util.getFail("保存数据过程中出现异常" + e.getMessage());
        }
        return Util.getSuccess();
    }


    @PostMapping("/data")
//    @ApiOperation(value = "根据请求参数新增数据")
//    @ApiImplicitParam(name = "param", value = "请求参数", paramType = "body", required = true, dataType = "Json",
//            examples = @Example({
//                    @ExampleProperty(value = GlobalConsts.EXAMPLE_ADD_DATA, mediaType = "application/json")
//            })
//    )
    public JSONObject add11(@RequestBody JSONObject param) throws Exception {
        ArrayList<Document> arrayList = new ArrayList<>();
        String table;
        if (param.containsKey("table")) {
            table = param.getString("table");
        } else {
            return Util.getFail("请求参数不包含表名称!");
        }

        if (param.containsKey("data")) {
            JSONArray data = param.getJSONArray("data");
            for (Object i : data) {
                JSONObject item = (JSONObject) i;
                Document doc = new Document();
                for (Map.Entry entry : item.entrySet()) {
                    String key = entry.getKey().toString();
                    Object value = entry.getValue();
                    if (StrUtil.isTimeKey(key)) {
                        value = DateUtil.convertStringToDate(value.toString());
                    }
                    doc.append(key, value);
                }
                arrayList.add(doc);
            }
        }
        try {
            addService.add(arrayList, table);
        } catch (Exception e) {
            LOG.warn("新增数据异常...", e);
            return Util.getFail("保存数据过程中出现异常" + e.getMessage());
        }
        return Util.getSuccess();
    }


    @PostMapping("/{num}")
    public JSONObject add(@PathVariable int num) {
        ArrayList<Entity> arrayList = new ArrayList<>();
        if (num > 10000) {
            return Util.getFail();
        }
        for (int i = 0; i < num; i++) {
            Entity entity = Util.getRandomEntity();
            arrayList.add(entity);
        }
        try {
            addService.add(arrayList);
        } catch (Exception e) {
            LOG.warn("新增数据异常...", e);
            return Util.getFail();
        }

        return Util.getSuccess();
    }


    public JSONObject addCar(int num) {
        ArrayList<Object> arrayList = new ArrayList<>();
        if (num > 10_0000) {
            return Util.getFail();
        }
        for (int i = 0; i < num; i++) {
            JSONObject multobj = JSONObject.parseObject(MopzingMongodbApplication.str);
            multobj.put("plateNumber", Util.generateCarID());
            multobj.put("time", Util.getTimeBetweenSomeDay(30));
            arrayList.add(multobj);
        }
        try {
            addService.addObjList(arrayList);
        } catch (Exception e) {
            LOG.warn("新增数据异常...", e);
            return Util.getFail();
        }

        return Util.getSuccess();
    }

    @PostMapping("/trigger/{num}")
    public JSONObject addBegin(@PathVariable int num) {
        for (int i = 1; i <= num; i++) {
            addCar(10000);
            LOG.info("新增10000条数据成功...");
        }
        JSONObject json = new JSONObject();
        json.put("response", "新增:" + num * 10000 + "条数据成功!");
        return json;
    }

    @PostMapping("/addUser")
    public JSONObject addUser(@RequestBody JSONObject param) throws Exception {
        ArrayList<Document> arrayList = new ArrayList<>();
        String table;
        if (param.containsKey("table")) {
            table = param.getString("table");
        } else {
            return Util.getFail("请求参数不包含表名称!");
        }
        ArrayList<String> arr = new ArrayList(512);

        for (int i = 0; i < 256; i++) {
            arr.add(i + "---");
        }

        if (param.containsKey("data")) {
            JSONArray data = param.getJSONArray("data");
            int begin = 0;
            for (int num = 0; num < 100; num++) {
                for (int i = 0; i < 1000; i++) {
                    Document doc = new Document();
                    int id = begin++;
                    doc.append("id", id);
                    doc.append("name", "mozping" + id);
                    doc.append("data", arr);
                    arrayList.add(doc);
                }
                addService.add(arrayList, table);
                arrayList.clear();
            }
            return Util.getSuccess();
        } else {
            return Util.getFail("请求参数不包含数据!");
        }
    }


    @GetMapping("/addMultobj/trigger/{num}")
    public JSONObject addMultobjBatch(@PathVariable int num) throws Exception {
        for (int i = 1; i <= num; i++) {
            addMultobj(10000);
            LOG.info("新增10000条数据成功...");
        }
        JSONObject json = new JSONObject();
        json.put("response", "新增:" + num * 10000 + "条数据成功!");
        return json;
    }


    private void addMultobj(int num) throws Exception {
        ArrayList<Document> arrayList = new ArrayList<>(1000);

        int roop = num / BATCH;
        for (int j = 1; j <= roop; j++) {
            for (int i = 1; i <= BATCH; i++) {
                Document randomObj = RandomObjFactory.getRandomObj();
                randomObj.put("time", Util.getTimeBetween3Month());
                arrayList.add(randomObj);
            }
            addService.add(arrayList, "multobj");
            LOG.info("新增" + BATCH + "条数据成功...");
            arrayList.clear();
        }
    }


}
